package com.simple.datax.seda.core;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.simple.datax.seda.api.EventHandlerIF;
import com.simple.datax.seda.api.QueueElementIF;
import com.simple.datax.seda.api.QueueIF;
import com.simple.datax.seda.api.StageWrapperIF;
import com.simple.datax.seda.api.ThreadManagerIF;
import com.simple.datax.seda.core.exception.InitFailedException;

public class MultiThreadStage implements StageWrapperIF {

	private Log LOG = LogFactory.getLog(MultiThreadStage.class);

	int threadCount = 1;
	String name;
	EventHandlerIF eventHandler;
	QueueIF queue;
	MultiThreadManager threadManager;

	// ConfigInfoIF config = null;

	// StageStatistic stageStatistic;

	public void Initialize() throws InitFailedException {
		if (name == null || name.trim().equals("")) {
			throw new InitFailedException("处理平台的 name 属性是空.");
		}
		if (threadCount < 1) {
			throw new InitFailedException("处理平台的 [" + name
					+ "] 的 threadCount 属性是负数[" + threadCount + "].");
		}
		if (this.eventHandler == null) {
			throw new InitFailedException("处理平台的 [" + name
					+ "] 的 eventHandler 属性是空.");
		}
		this.threadManager = new MultiThreadManager(name);
		this.threadManager.setThreadCount(threadCount);
		this.threadManager.setStageWrapper(this);
		this.threadManager.initialize();

		eventHandler.initialize();
		this.queue = new UnboundedQueue();
		LOG.info("处理平台 [" + this.name + "] 初始化成功.");
	}

	public MultiThreadStage() throws InitFailedException {

		this.name = name;
		this.eventHandler = null;

		// this.stageStatistic = new StageStatistic();

	}

	public boolean isAlive() {
		return threadManager.isAlive();

	}

	public void start() {
		this.threadManager.start();
		LOG.info("处理平台 [" + this.name + "] 启动成功.");
	}

	// public EventStatistic getEventStatistic(String eventClassName){
	// return this.stageStatistic.getEventHandlerStatistic(eventClassName);
	// }

	public EventHandlerIF getEventHandler() {
		return this.eventHandler;
	}

	public void setEventHandler(EventHandlerIF eventHandler) {
		this.eventHandler = eventHandler;
	}

	public boolean putEvent(QueueElementIF event) {
		return this.queue.enqueue(event);
	}

	public QueueElementIF pollEvent() {
		return this.queue.dequeue();
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	/**
	 * 
	 * @return
	 */
	public ThreadManagerIF getThreadManager() {
		return this.threadManager;
	}

	public int getThreadCount() {
		return threadCount;
	}

	public void setThreadCount(int threadCount) {
		this.threadCount = threadCount;
	}

}
